(function($, main) {
  var instances = {};
  main.uploader = function(obj, id, opt) {
    opt = $.extend({
      url: '',				        	// 图片上传地址
      name: '',					        // 上传文件的name值
      success: function() {},	  // 成功是执行的函数
      error: function() {},	  	// 失败时执行的函数
      finish: function() {},		// 完成时执行的函数（成功或失败都执行）
      accept:  {},			      	// 允许的文件类型
      formData: {}			      	// 附加数据
    }, opt);
    if (instances[id]) {
      instances[id].destroy();
      $('#' + id).removeAttr('id');
    }
    return instances[id] = Uploader.create(obj, id, opt);
  };
  function Uploader(obj, id, opt) {
    $.extend(this, opt);
    obj.find('.webuploader-file-picker').attr('id', id);
    var uploader = WebUploader.create({
      auto: true,            	// 选完文件后，是否自动上传
      server: this.url,      	// 文件上传地址
      pick: '#' + id, 	      // 选择文件的按钮
      fileVal: this.name,    	// 上传文件name指值
      duplicate: true,       	// 允许重复上传同一张图片
      accept: this.accept,   	// 允许的文件类型
      formData: this.formData	// 附加数据
    });
    var that = this;
    var status = obj.find('.webuploader-status');
    var statusItems = {};
    uploader.on('uploadBeforeSend', function(obj, data, headers) {
      statusItems[obj.file.id] = Status.create(status);
      statusItems[obj.file.id].name.text(obj.file.name);
      headers['X-CSRF-TOKEN'] = main.token;
    });
    uploader.on('uploadProgress', function (file, percentage) {
      per = parseInt(percentage * 100) + '%';
      statusItems[file.id].progressBar.css('width', per);
      statusItems[file.id].progressPer.html(per);
    });
    uploader.on('uploadComplete', function (file) {
      statusItems[file.id].obj.fadeOut('fast', function() {
        $(this).remove();
      })
    });
    uploader.on('uploadFinished', function() {
      that.finish();
    });
    uploader.on('uploadSuccess', function (file, response) {
      if (response.code === 0) {
        main.toastr.error(file.name + ' ' + response.msg);
      }
      that.success(file, response);
    });
    uploader.on('uploadError', function (file, reason) {
      main.toastr.error(file.name + ' 上传失败，服务器异常。');
        that.error(file, reason);
    });
    return uploader;
  }
  Uploader.create = function(obj, id, opt) {
    return new Uploader(obj, id, opt);
  };
  function Status(obj) {
    this.obj = $('<div class="webuploader-status-item"></div>').appendTo(obj);
    this.name = $('<span class="webuploader-status-name"></span>').appendTo(this.obj);
    this.progress = $('<span class="webuploader-status-progress"></span>').appendTo(this.obj);
    this.progressBar = $('<i></i>').appendTo(this.progress);
    this.progressPer = $('<span class="webuploader-status-per">0%</span>').appendTo(this.obj);
  }
  Status.create = function(obj) {
    return new Status(obj);
  };
})(jQuery, main);